package com.lemeng.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.lemeng.dao.UserMapper;

import com.lemeng.entity.Result;
import com.lemeng.pojo.User;
import com.lemeng.service.UserService;
import com.lemeng.util.BCrypt;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.TimeUnit;


@Service(interfaceClass = UserService.class)
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public void sendSms(String phone) {


        //生成验证码
        Random random = new Random();
        int code = random.nextInt(10000);
        if (code < 1000){
            code = 10000+1;
        }

        //存入redis,验证验证码是否正确时使用
        redisTemplate.boundValueOps("code_"+phone).set(code,5, TimeUnit.MINUTES);

        //发送到mq,(发送手机验证码短信时使用)

        HashMap map = new HashMap();
        map.put("phone",phone);
        map.put("code",code);
        rabbitTemplate.convertAndSend("","queue.sms", JSONObject.toJSONString(map));
    }

    @Override
    public void register(String code, User user) {
        User searchUser = new User();
        searchUser.setPhone(user.getPhone());

        if (userMapper.selectCount(searchUser) > 0){
            throw new RuntimeException("手机号已被注册");
        }
        Object redisCode = redisTemplate.boundValueOps("code_" + user.getPhone()).get();
        if (redisCode == null){
            throw new RuntimeException("验证码已过期");
        }

        if (!code.equals(redisCode.toString())){
            throw new RuntimeException("验证码错误");
        }

        Date date = new Date();
        user.setPassword(BCrypt.hashpw(user.getPassword(),BCrypt.gensalt()));
        user.setUsername(user.getPhone());
        user.setCreated(date);
        user.setUpdated(date);
        user.setSourceType("1");
        user.setStatus("1");
        user.setIsMobileCheck("1");

        userMapper.insertSelective(user);

    }
}
